package com.gzbsoft.sc.common.config;
import com.gzbsoft.sc.common.utils.ShiroUtils;
import com.gzbsoft.sc.modules.sys.dao.JxUserDao;
import com.gzbsoft.sc.modules.sys.entity.JxUser;
import io.ebean.config.CurrentUserProvider;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Optional;
@Configuration
public class EbeanCurrentUserProvider implements CurrentUserProvider {
    private final JwtConfig jwtConfig;
    private final JxUserDao jxUserDao;
    public EbeanCurrentUserProvider(JwtConfig jwtConfig, @Lazy JxUserDao jxUserDao) {
        this.jwtConfig = jwtConfig;
        this.jxUserDao = jxUserDao;
    }
    @Override
    public Object currentUser() {
        if (Optional.ofNullable(ShiroUtils.getUserEntity()).isPresent()) {
            return ShiroUtils.getUserEntity().getUsername();
        } else {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) {
                return "";
            }
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader(jwtConfig.getHeader());
            Long userId = Long.valueOf(jwtConfig.getClaimByToken(token).getSubject());
            return jxUserDao.findById(userId).map(JxUser::getUsername).orElse(null);
        }
    }
}
